<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form :model="userForm" :rules="userFormRules" ref="userFormRef" label-width="100px">
      <el-form-item label="登录名称" prop="username">
        <el-input v-model="userForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="userForm.nickname" minlength="1" maxlength="10"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userForm.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitFn">提交修改</el-button>
        <el-button @click="resetFn">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import user from '@/api/user'

export default {
  name: 'UserInfo',
  components: {},
  data () {
    return {
      userForm: {
        id: 0,
        username: '',
        nickname: '',
        email: ''
      },
      userFormRules: {
        nickname: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          {
            pattern: /^\S{1,10}$/,
            message: '用户昵称必须是1-10的非空字符串',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入一个合法邮箱', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  methods: {
    submitFn () {
      this.$refs.userFormRef.validate(async valid => {
        if (valid) {
          // 通过校验
          const { data: res } = await user.updateUserInfo(this.userForm)
          if (res.code === 0) {
            // 更新vuex最新用户信息
            this.$store.dispatch('initUserInfo')
            this.$message.success(res.message)
          } else {
            this.$message.info(res.message)
          }
        } else {
          return false
        }
      })
    },
    resetFn () {
      /* this.userForm.nickname = ''
      this.userForm.email = '' */

      // 既能重置初始值，也能重置错误提示
      this.$refs.userFormRef.resetFields()
    }
  },
  created () {
    const { id, username, nickname, email } = this.$store.state.userInfo
    this.userForm.id = id
    this.userForm.username = username
    this.userForm.nickname = nickname
    this.userForm.email = email
  },
  mounted () {

  }
}
</script>
<style scoped>
.el-form {
  width: 40%;
}
</style>
